package com.stox.downloader.yahoo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.stox.core.model.Bar;
import com.stox.core.model.Scrip;
import com.stox.core.util.Constant;
import com.stox.core.util.StringUtil;
import com.stox.downloader.DataStream;
import com.stox.downloader.DataStreamParser;

public class YahooDataStreamParser implements DataStreamParser {

	private String format = "d1ohgl1pv";
	private SimpleDateFormat yahooDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	
	public String getFormat() {
		return format;
	}
	
	public List<Bar> parse(String text, Scrip scrip) {
		if(StringUtil.hasText(text)){
			String[] tokens = text.split(Constant.lineSeparator);
			List<Bar> barList = new ArrayList<Bar>(tokens.length);
			for(String token : tokens){
				Bar bar = parseInternal(token, scrip);
				if(bar != null){
					barList.add(bar);
				}
			}
			return barList;
		}
		return null;
	}

	private Bar parseInternal(String text, Scrip scrip){
		if(StringUtil.hasText(text)){
			Bar bar = new Bar();
			String[] tokens = text.split(",");
			try {
				bar.setDate(yahooDateFormat.parse(tokens[0].replaceAll("\"", "")));
				bar.setScripCode(scrip.getCode());
				bar.setOpen(Double.parseDouble(tokens[1]));
				bar.setHigh(Double.parseDouble(tokens[2]));
				bar.setLow(Double.parseDouble(tokens[3]));
				bar.setClose(Double.parseDouble(tokens[4]));
				bar.setVolume(Double.parseDouble(tokens[6]));
				//bar.setPreviousClose(Double.parseDouble(tokens[5]));
				return bar;
			} catch (Exception e) {
			
			}
		}
		return null;
	}

	@Override
	public DataStream parse(String rawData) {
		
		return null;
	}
	
}
